package com.umeox.watch.moto.sos;

import android.animation.ValueAnimator;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.WindowManager;
import android.widget.TextView;

import com.tencent.mmkv.MMKV;
import com.umeox.moto.common.log.Logger;
import com.umeox.moto.watch.themes.app.ThemeAppCompatActivity;
import com.umeox.moto.watch.themes.widget.ProgressView;

import java.util.Locale;

/**
 * 按下 SOS 键出来的请求页面
 */
public class SOSActivity extends ThemeAppCompatActivity implements SOSService.SOSCallback {

    private TextView recordTips;
    private ProgressView pvCountdown;
    private ValueAnimator increaseAnimator;
    private SOSService mService;
    private Handler mHandler;
    private int maxDurationMs = 30000;
    private boolean mStartLocationing;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.act_sos);
        Logger.e("============onCreate===========");
        MMKV.defaultMMKV().encode(BaseApp.SOS_STATUS, true);
        mHandler = new Handler();
        recordTips = findViewById(R.id.tvCountdown);
        pvCountdown = findViewById(R.id.pvCountdown);
        pvCountdown.setProgress(0);

        mService = SOSService.createTask(maxDurationMs, SOSActivity.this, getApplicationContext());
        mService.startService();
    }

    @Override
    public void onBackPressed() {
    }

    private static final String TAG = "SOSonTick";

    @Override
    public void onTick(int secsUntilFinished, float percent) {

        pvCountdown.setProgress(percent);

        final String format = String.format(Locale.getDefault(), "%d\"", secsUntilFinished);
        recordTips.setText(format);

        if (secsUntilFinished <= 13) {
            if (!mStartLocationing) {
                mStartLocationing = true;
                mService.startLocation();
            }
        }
    }

    @Override
    public void onFinish(boolean state) {
        MMKV.defaultMMKV().encode(BaseApp.SOS_STATUS, false);
        this.finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: " + this);
        if (!mStartLocationing) {
            mService.cancel();
        }

        MMKV.defaultMMKV().remove(BaseApp.SOS_STATUS);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        mHandler.removeCallbacksAndMessages(null);
    }
}
